package org.yinweichen.llm_dataset_backend.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;

public final class ModelApiClient {
    private static final String API_BASE_URL = "https://chatgtp.vin";
    private static final String API_ENDPOINT = "/v1/chat/completions";
    private static String API_KEY = System.getenv("LLM_API_KEY");
    @Setter
    @Getter
    private static volatile String currModel = "deepseek-chat";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    private ModelApiClient() {
        throw new UnsupportedOperationException("工具类不允许实例化");
    }

    public static String getAPIKey() {
        if (API_KEY == null || API_KEY.isEmpty()) {
            throw new IllegalStateException("LLM_API_KEY环境变量未设置");
        }
        return API_KEY;
    }

    public static void setAPIKey() {
        API_KEY = System.getenv("LLM_API_KEY");
    }

    public static String getAnswer(String prompt, String userQuestion) {
        return getAnswer(prompt, userQuestion, 1024);
    }

    public static String getAnswer(String prompt, String userQuestion, int maxTokens) {
        // 确保API_KEY已设置
        getAPIKey();
        try {
            // 构建请求体结构
            Map<String, Object> requestBody = Map.of(
                "model", currModel,
                "messages", List.of(
                    Map.of("role", "system", "content", prompt),
                    Map.of("role", "user", "content", userQuestion)
                ),
                "temperature", 0.7,
                "max_tokens", maxTokens
            );

            // 序列化为JSON字符串
            String requestBodyJson = objectMapper.writeValueAsString(requestBody);

            // 创建HTTP客户端
            HttpClient client = HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(30))
                    .build();

            // 构建HTTP请求，设置1分钟超时
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(API_BASE_URL + API_ENDPOINT))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + API_KEY)
                    .timeout(Duration.ofMinutes(1))  // 设置1分钟超时
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyJson))
                    .build();

            System.out.println("请求体: " + requestBodyJson);
            System.out.println("Max tokens: " + maxTokens);
            // 发送请求并获取响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // 处理响应
            if (response.statusCode() == 200) {
                Map<String, Object> responseMap = objectMapper.readValue(response.body(), Map.class);
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
                Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                return (String) message.get("content");
            } else {
                throw new IOException("API请求失败，状态码: " + response.statusCode() +
                                    "，响应内容: " + response.body());
            }

        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON处理错误: " + e.getMessage(), e);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException("API请求出错: " + e.getMessage(), e);
        }
    }
}